<template>
 <div>
<!--   搜索框-->
   <div class="divTop" v-model="search">
     <span>部门名称</span><el-input v-model="search.deptName" style="width: 250px" placeholder="请输入部门名称"></el-input>
     <span>部门状态</span><el-select v-model="search.status" placeholder="请选择部门状态">
     <el-option label="正常" value="0"></el-option>
     <el-option label="停用" value="1"></el-option>
      </el-select>
     <el-button class="souSuoBut" @click="selectDeptAll" type="success" size="small" icon="el-icon-search">搜索</el-button>
     <el-button @click="searchCZ" size="small" icon="el-icon-refresh">重置</el-button>
   </div>
<!--   添加按钮-->
   <el-button class="addBut" type="primary" size="medium" @click="doSave('dept')">添加</el-button>
<!--   数据展示-->
   <el-table
       :data="depts"
       style="width: 100%"
       row-key="deptId"
       default-expand-all
       :tree-props="{children: 'childDept', hasChildren: 'hasChildren'}">
     <el-table-column
         prop="deptName"
         label="部门名称">
     </el-table-column>
     <el-table-column
         prop="orderNum"
         label="排序">
     </el-table-column>
     <el-table-column
         prop="status"
         label="状态">
       <template slot-scope="scop">
         <span v-if="scop.row.status == '0'">正常</span>
         <span v-if="scop.row.status == '1'">停用</span>
       </template>
     </el-table-column>
     <el-table-column
         header-align="center"
         align="center"
         prop="createTime"
         label="创建时间">
     </el-table-column>
     <el-table-column
         header-align="center"
         align="center"
         label="操作">
       <template slot-scope="scope">
         <el-button @click="doEdit(scope.row,'dept')" type="text" size="small">修改</el-button>
         <el-button @click="doAddSave(scope.row,'dept')" type="text" size="small">新增</el-button>
         <el-button v-if="scope.row.parentId!=0" @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
       </template>
     </el-table-column>
   </el-table>
   <!--  添加或修改弹窗-->
   <el-dialog title="部门管理" :visible.sync="dept_window" width="600px" append-to-body>
     <el-form ref="dept" :model="dept" :rules="deptRules" label-width="80px">
       <el-row>
           <el-form-item v-show="dept.parentId!=0" label="上级部门" prop="parentId">
             <!-- 添加或修改菜单对话框 -->
               <Treeselect
                   v-model="dept.parentId"
                   :options="deptShu"
                   :placeholder="'请选择人员'"
                   :normalizer="normalizer"
                   :multiple="false"
               />
           </el-form-item>
       </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="部门名称" prop="deptName">
             <el-input v-model="dept.deptName" placeholder="请输入部门名称" />
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="显示排序" prop="orderNum">
             <el-input-number v-model="dept.orderNum" controls-position="right" :min="0" />
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="负责人" prop="leader">
             <el-input v-model="dept.leader" placeholder="请输入负责人" maxlength="20" />
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="联系电话" prop="phone">
             <el-input v-model="dept.phone" placeholder="请输入联系电话" maxlength="11" />
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="邮箱">
             <el-input v-model="dept.email" placeholder="请输入邮箱" maxlength="50" />
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="部门状态">
             <el-radio-group v-model="dept.status" @change="statusDJ">
               <el-radio :label="0" >正常</el-radio>
               <el-radio :label="1" >禁用</el-radio>
             </el-radio-group>
           </el-form-item>
         </el-col>
       </el-row>
     </el-form>
     <div slot="footer" class="dialog-footer">
       <el-button type="primary" @click="save('dept')">确 定</el-button>
       <el-button @click="dept_window=false">取 消</el-button>
     </div>
   </el-dialog>

 </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: {Treeselect},
  name: "DeptView",
  data() {
    return {
      depts:[],
      //搜索实体
      search:{deptName:null,status:null},
      dept:{"deptId":null,"parentId":null,"ancestors":null,"deptName":"","orderNum":null,"leader":null,"phone":null,"email":null,"status":0,"delFlag":null,"createBy":null,"createTime":null,"updateBy":null,"updateTime":null},
      dept_window:false,
      deptShu:[],   //添加用的部门树
      defaultDepts: {
        children: 'childDept',
        label: 'deptName'
      },
      deptRules:{
        parentId:[{required: true, message: '上级部门不能为空', trigger: 'blur' }],
        deptName:[{required: true, message: '部门名称不能为空', trigger: 'blur' }],
        orderNum:[{required: true, message: '显示排序不能为空', trigger: 'blur' }],
        leader:[{required: true, message: '负责人不能为空', trigger: 'blur' }],
        phone:[{required: true, message: '负责人电话不能为空', trigger: 'blur' }],
      },


    }
  },
  methods:{
    //查询
    selectDeptAll(){
      this.$axios.post("/sysDept/selectDeptAll",{
        deptName:this.search.deptName,
        status:this.search.status
      })
          .then(result =>{
            if (result.data.code==200){
              console.log(result.data.data)
              this.depts = result.data.data;
            }
          })
    },
    //搜索重置点击
    searchCZ(){
      this.search={roleName:null,roleKey:null,status:null,time:[]};
      this.selectDeptAll();
    },
    //点击主添加按钮打开弹窗
    doSave(dept){
      this.selectDepts();
      this.dept={"deptId":null,"parentId":null,"ancestors":null,"deptName":"","orderNum":null,"leader":null,"phone":null,"email":null,"status":0,"delFlag":null,"createBy":null,"createTime":null,"updateBy":null,"updateTime":null};
      this.dept_window = true;
      this.$refs[dept].resetFields();
    },
    //点击添加打开弹窗
    doAddSave(dept,qwe){
      this.selectDepts();
      this.dept={"deptId":null,"parentId":null,"ancestors":null,"deptName":"","orderNum":null,"leader":null,"phone":null,"email":null,"status":0,"delFlag":null,"createBy":null,"createTime":null,"updateBy":null,"updateTime":null};
      this.dept.parentId = dept.deptId;
      this.dept.ancestors = dept.ancestors +","+ dept.deptId;
      this.dept_window = true;
      this.$refs[qwe].resetFields();
    },
    //修改前的初始化
    doEdit(dept,qwe){
      this.selectDepts();
      this.dept=JSON.parse(JSON.stringify(dept));
      //判断状态
      if (dept.status == '0'){
        this.dept.status=0;
      }else {
        this.dept.status=1;
      }
      this.dept_window = true;
      this.$refs[qwe].resetFields();
    },
    //查询部门树
    selectDepts(){
      this.$axios.get("/sysDept/deptTree")
          .then(result =>{
            if (result.data.code==200){
              this.deptShu = result.data.data;
            }
          })
    },
    //下拉框+树形控件
    normalizer(node) {
      // 去掉children=[]的children属性
      if (node.childDept && !node.childDept.length || node.childDept == null) {
        delete node.childDept;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.childDept,
      }
    },
    //添加或修改弹窗
    save(dept){
      if (this.dept.deptId==null){//添加
        this.$refs[dept].validate((valid) => {
          if (valid) {
            console.log(this.dept)
            // localStorage.getItem("userName") //传入登录用户名，也就是创建角色用户
            this.dept.createBy=localStorage.getItem("username");//测试给默认值后续删
            this.$axios.post("/sysDept/deptAdd",this.dept)
                .then(result =>{
                  if (result.data.code==200){
                    this.dept_window = false;
                    this.selectDeptAll();
                    this.$message({
                      message: '恭喜你，'+result.data.data,
                      type: 'success'
                    });
                  }else {
                    this.$message({
                      message: '警告哦，'+result.data.message,
                      type: 'warning'
                    });
                  }
                })
          } else {
            console.log("没写完")
            return false;
          }
        });

      }else {//修改
        // localStorage.getItem("userName") //传入登录用户名，也就是创建角色用户
        this.dept.updateBy=localStorage.getItem("username");//测试给默认值后续删
        this.$axios.put("/sysDept/deptEdit",this.dept)
            .then(result =>{
              if (result.data.code==200){
                this.dept_window = false;
                this.selectDeptAll();
                this.$message({
                  message: '恭喜你，'+result.data.data,
                  type: 'success'
                });
              }else {
                this.$message({
                  message: '警告哦，'+result.data.message,
                  type: 'warning'
                });
              }
            })
      }
    },
    //状态点击
    statusDJ(){
      //判断有无未停用的子部门
      if(this.dept.status =='1' && this.dept.deptId != null){
        this.$axios.get("/sysDept/selectChildDept/"+this.dept.deptId)
            .then(result =>{
              if (result.data.code==200){
                if (result.data.data=='no'){
                  console.log("有子部门")
                  this.$notify.error({
                    title: '错误',
                    message: '当前部门还有未停用的子部门'
                  });
                  this.dept.status=0;
                }
              }
            })
      }

      //判断当前部门的是否有父部门且是否停用
      if(this.dept.status=='0' && this.dept.deptId != null){
        this.$axios.get("/sysDept/selectFatherDept/"+this.dept.parentId)
            .then(result =>{
              if (result.data.code==200){
                if (result.data.data=='no'){
                  console.log("父部门未启用")
                  this.$notify.error({
                    title: '错误',
                    message: '当前部门的父级部门未启用'
                  });
                  this.dept.status=1;
                }
              }
            })
      }
    },
    //删除并判断是否有子部门
    handleDelete(dept) {
      let deptId = dept.deptId;
      this.$confirm(`确定删除部门编码为 ${deptId} 的部门吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (dept.childDept && dept.childDept.length > 0) {
          // 有子目录，禁止删除
          this.$message.error('该部门有子部门，无法删除');
          return;
        }
        this.$axios.delete('/sysDept/deleteDept/' + deptId)
            .then(result => {
              if (result.data.data) {
                this.selectDeptAll();
                this.$message({
                  type: 'success',
                  message: result.data.data,
                });
              }
            })
      }).catch(() => {
        // 用户点击取消的处理逻辑
        this.selectDeptAll();
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

  },
  mounted() {
    this.selectDeptAll();
  }
}
</script>

<style scoped>
.divTop{
  margin-bottom: 20px;
  text-align: left;
}
.divTop>span{
  margin-right: 10px;
  margin-left: 20px;
}
.souSuoBut{
  margin-left: 20px;
}
.addBut{
  float: left;
  margin-left: 20px;
  margin-bottom: 10px;
}
</style>